import React, { memo, useState, useEffect, useRef } from 'react'
import style from './sty.module.css'

import { CSSTransition } from 'react-transition-group'

// import animations from 'create-keyframe-animation'
import ProgressBar from '@/components/ProgressBar'
import { formatTime } from '@/utils/util'
import Scroll from '@/components/scroll'
import { shallowEqual, useSelector } from 'react-redux'

let timer = null
const NormalPlayer = () => {

    const [currentShow, setCurShow] = useState('cd');
    const middleL = useRef(null)
    const middleR = useRef(null)
    const cdWrapper = useRef(null)
    const lyricRef = useRef(null)
    useEffect(() => {
        scrollToCurrent()
    }, [])

    const lineNum = 5
    const scrollToCurrent = () => {
        // clearTimeout(timer)

        // if (lineNum > 5) {
        //     let lineEl = this[`lyricLine${lineNum - 5}`]
        //     this.lyricList && this.lyricList.scrollToElement(lineEl, 1000)
        // } else {
        //     this.lyricList && this.lyricList.scrollTo(0, 0, 1000)
        // }
    }

    const close = () => {
        this.props.appStore.setFullScreen(false)
    }
    const _getPosAndScale = () => {
        const targetWidth = 40
        const paddingLeft = 40
        const paddingBottom = 30
        const paddingTop = 80
        const width = window.innerWidth * 0.8
        const scale = targetWidth / width
        const x = -(window.innerWidth / 2 - paddingLeft)
        const y = window.innerHeight - paddingTop - width / 2 - paddingBottom
        return {
            x,
            y,
            scale
        }
    }
    const onEnter = () => {

    }
    const togglePlay = () => {
        this.props.appStore.togglePlay()
    }
    const setLikes = () => {
        this.props.appStore.setLikes(this.props.appStore.currentSong)
    }
    const changeMode = () => {
        this.props.appStore.changeMode()
    }
    const prev = () => {
        this.props.appStore.changeSong('prev')
    }
    const next = () => {
        this.props.appStore.changeSong('next')
    }
    const onPercentChange = (percent) => {
        this.props.appStore.onPercentChange(percent)
    }
    const middleTouchStart = (e) => {
        const touch = e.touches[0]
        this.touch = {
            startX: touch.pageX,
            startY: touch.pageY,
        }
    }
    const middleTouchMove = (e) => {
        if (!this.touch) {
            return
        }
        const touch = e.touches[0]
        //计算X、Y方向的移动距离
        const offsetX = touch.pageX - this.touch.startX
        const offsetY = touch.pageY - this.touch.startY
        if (Math.abs(offsetY) > Math.abs(offsetX)) {
            //如果Y轴方向移动距离大于X轴则return
            return
        }
        const left = currentShow === 'cd' ? 0 : -window.innerWidth
        const translateX = Math.min(0, Math.max(-window.innerWidth, left + offsetX))
        this.touch.percent = Math.abs(translateX / window.innerWidth)
        const opacity = 1 - this.touch.percent
        this.animationDom(translateX, opacity, 0)

    }
    const middleTouchEnd = () => {
        let translateX = 0
        let opacity = 0
        if (currentShow === 'cd') {
            if (this.touch.percent > 0.1) {
                translateX = -window.innerWidth
                opacity = 0
                this.setState({
                    currentShow: 'lyric'
                })
            } else {
                translateX = 0
                opacity = 1
            }
        } else {
            if (this.touch.percent < 0.9) {
                translateX = 0
                opacity = 1
                this.setState({
                    currentShow: 'cd'
                })
            } else {
                translateX = -window.innerWidth
                opacity = 0
            }
        }
        animationDom(translateX, opacity, 300)
        this.timer = setTimeout(() => {
            scrollToCurrent()
        }, 1000)
        this.touch = null

    }
    const animationDom = (translateX, opacity, duration) => {
        this.middleR.style.transform = `translateX(${translateX}px)`
        this.middleR.style.transitionDuration = `${duration}ms`
        this.middleL.style.opacity = opacity
        this.middleL.style.transitionDuration = `${duration}ms`
    }
    const playingLineNum = 5;

    const { currentSong, isFullScreen, playing, likeSongs, mode, percent, currentTime, songReady, playingLyric, lyric, } = useSelector(state => ({
        currentSong: state.getIn(['curSong']),
        isFullScreen: state.getIn(['isFullScreen']),
        playing: state.getIn(['playing']),
        likeSongs: state.getIn(['likeSongs']),
        mode: state.getIn(['sequence']),
        percent: state.getIn(['percent']),
        currentTime: state.getIn(['curTime']),
        songReady: state.getIn(['songReady']),
        playingLyric: state.getIn(['curLyrIdx']),
        lyric: state.getIn(['lyric']),

    }), shallowEqual)

    const isExist = likeSongs.some(item => item.id === currentSong.id)
    const icons = ['icon-xunhuanbofang', 'icon-suijibofang', 'icon-danquxunhuan']

    return (
        <CSSTransition
            onEnter={onEnter}
            timeout={300}
            classNames={'normal'}
            in={isFullScreen}>
            <div className={style['normal-player']} style={{ display: isFullScreen ? '' : 'none' }}>
                <div className={style.background}>
                    <img src={currentSong.image} alt='' />
                </div>
                <div className={`${style.top} top`}>
                    <div className={style.back} onClick={close}>
                        <span className={'iconfont icon-jiantouarrow483'} />
                    </div>
                    <h2>{currentSong.name}</h2>
                    <h3>{currentSong.artists}</h3>
                </div>
                <div className={style.middle} onTouchStart={middleTouchStart}
                    onTouchMove={middleTouchMove} onTouchEnd={middleTouchEnd}>
                    <div className={style['middle-left']} ref={middleL}>
                        <div className={style['image-wrapper']} ref={cdWrapper}>
                            <img src={currentSong.image} alt=""
                                className={`rotate ${playing ? '' : 'rotate-pause'}`} />
                        </div>
                        <div className={style['playing-lyric-wrapper']}>
                            <div className={style['playing-lyric']}>{songReady ? playingLyric : '正在缓冲...'}</div>
                        </div>
                    </div>
                    <div className={style['middle-right']} ref={middleR}>
                        <div className={style['lyric-wrapper']}>
                            <Scroll ref={lyricRef}>
                                <ul>
                                    {lyric && lyric.map((item, index) => <li key={index}
                                        ref={lyricLine => this[`lyricLine${index}`] = lyricLine}
                                        className={`${style.text} ${playingLineNum === index ? style.current : ''}`}>{item.txt}</li>)}
                                </ul>
                            </Scroll>
                        </div>
                    </div>
                </div>
                <div className={`${style.bottom} bottom`}>
                    <div className={style['dot-wrapper']}>
                        <span className={`${style.dot} ${currentShow === 'cd' ? style.active : ''}`} />
                        <span className={`${style.dot} ${currentShow === 'lyric' ? style.active : ''}`} />
                    </div>
                    <div className={style['progress-wrapper']}>
                        <div className={style.time}>{formatTime(currentTime)}</div>
                        <div className={style['bar-wrapper']}>
                            <ProgressBar percent={percent} percentChange={onPercentChange} />
                        </div>
                        <div className={style.time}>{formatTime(currentSong.duration)}</div>
                    </div>
                    <div className={`${style['control-wrapper']} ${songReady ? '' : style.disable}`}>
                        <div><span className={`iconfont ${icons[mode]}`} onClick={changeMode} /></div>
                        <div><span className={'iconfont icon-shangyishou'} onClick={prev} /></div>
                        <div><span className={`iconfont ${playing ? 'icon-bofang2' : 'icon-play_icon'}`}
                            onClick={togglePlay} /></div>
                        <div><span className={'iconfont icon-xiayishou'} onClick={next} /></div>
                        <div><span className={`iconfont ${isExist ? 'icon-xihuan1' : 'icon-xihuan'}`}
                            onClick={setLikes} />
                        </div>
                    </div>
                </div>
            </div>
        </CSSTransition>
    )

}

export default memo(NormalPlayer)